package com.example.xianji.activity;

import java.io.InputStream;
import java.net.URL;
import java.text.SimpleDateFormat;

import org.json.JSONException;
import org.json.JSONObject;

import com.example.xianji.Contant;
import com.example.xianji.R;
import com.example.xianji.constant.Constant;
import com.example.xianji.utils.sp.PreferenceEngine;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class Main_Message_LoginActivity extends Activity implements OnClickListener {
    private TextView putong_login;
    private ImageView message_login_back, message_login_imageview;
    private EditText message_login_edtitText_name, tuxing_yanzheng, editText_yanzhengma;
    private Drawable d;
    private Button dongtai_login_yanzheng, message_login;
    private TimeCount mTimeCount;
    //    private SharedPreferences sp;
//    private Editor ed;
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                message_login_imageview.setImageDrawable(d);
            }
            if (msg.what == 2) {
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
        setContentView(R.layout.activity_main__message__login);
//        sp = getSharedPreferences("text", MODE_PRIVATE);
//        ed = sp.edit();

        //XJApplication.getInstance().addActivity(this);
        putong_login = (TextView) findViewById(R.id.putong_login);
        message_login_back = (ImageView) findViewById(R.id.message_login_back);
        message_login_edtitText_name = (EditText) findViewById(R.id.message_login_edtitText_name);
        message_login_imageview = (ImageView) findViewById(R.id.message_login_imageview);
        dongtai_login_yanzheng = (Button) findViewById(R.id.dongtai_login_yanzheng);
        tuxing_yanzheng = (EditText) findViewById(R.id.tuxing_yanzheng);
        message_login = (Button) findViewById(R.id.message_login);
        editText_yanzhengma = (EditText) findViewById(R.id.editText_yanzhengma);

        mTimeCount = new TimeCount(60000, 1000);

        putong_login.setOnClickListener(this);
        message_login_back.setOnClickListener(this);
        dongtai_login_yanzheng.setOnClickListener(this);
        message_login.setOnClickListener(this);
        message_login_edtitText_name.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() == 11) {
                    new Thread(new Runnable() {

                        @Override
                        public void run() {
                            LoadImageFromWebOperations(Contant.tuxing_yanzheng + message_login_edtitText_name.getText().toString());
                        }
                    }).start();
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.putong_login) {
            startActivity(new Intent(Main_Message_LoginActivity.this, Main_LoginActivity.class));
            this.finish();
        } else if (v.getId() == R.id.message_login_back) {
            this.finish();
        } else if (v.getId() == R.id.dongtai_login_yanzheng) {
            if (tuxing_yanzheng.getText().toString().length() > 0) {
                mTimeCount.start();
                huoqu_message_yanzhengma();
            } else {
                Toast.makeText(Main_Message_LoginActivity.this, "请输入图形验证码", Toast.LENGTH_SHORT).show();
            }
        } else if (v.getId() == R.id.message_login) {
            if (editText_yanzhengma.getText().toString().length() > 0) {
                message_login();
            } else {
                Toast.makeText(Main_Message_LoginActivity.this, "请输入手机验证码", Toast.LENGTH_SHORT).show();
            }
        }
    }


    /**
     * 获取短信验证
     */
    public void huoqu_message_yanzhengma() {
        HttpUtils httpUtils = new HttpUtils();
        RequestParams parms = new RequestParams();
        parms.addBodyParameter("code_from", "info");
        parms.addBodyParameter("mobile", message_login_edtitText_name.getText().toString());
        parms.addBodyParameter("picverify", tuxing_yanzheng.getText().toString());
        httpUtils.send(HttpMethod.POST, Contant.message_yanzheng, parms, new RequestCallBack<String>() {

            @Override
            public void onFailure(HttpException arg0, String arg1) {
            }

            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                try {
                    JSONObject obj = new JSONObject(arg0.result);
                    Toast.makeText(Main_Message_LoginActivity.this, obj.getString("msg"), Toast.LENGTH_SHORT).show();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 动态登录
     */
    public void message_login() {
        HttpUtils httpUtils = new HttpUtils();
        RequestParams parms = new RequestParams();
        parms.addBodyParameter("mverify", editText_yanzhengma.getText().toString());
        parms.addBodyParameter("mobile", message_login_edtitText_name.getText().toString());
        parms.addBodyParameter("picverify", tuxing_yanzheng.getText().toString());
        httpUtils.send(HttpMethod.POST, Contant.message_login, parms, new RequestCallBack<String>() {

            @Override
            public void onFailure(HttpException arg0, String arg1) {
            }

            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                try {
                    JSONObject obj = new JSONObject(arg0.result);
                    Toast.makeText(Main_Message_LoginActivity.this, obj.getString("msg"), Toast.LENGTH_SHORT).show();

                    if (obj.getInt("status") == 1) {
                        PreferenceEngine.getInstance().putBoolean(Constant.SP.NAME, Constant.SP.KEY_XIANJI_DENGLU, true);
                        PreferenceEngine.getInstance().putString(Constant.SP.NAME, Constant.SP.KEY_XIANJI_TOKEN, obj.getJSONObject("data").getString("token"));
                        Contant.login_resume = 1;
                        //startActivity(new Intent(Main_Message_LoginActivity.this, MainActivity.class));
                        Main_Message_LoginActivity.this.setResult(Contant.dongtai_login_success_back);
                        Main_Message_LoginActivity.this.finish();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 通过URL加载ImageView
     *
     * @param url
     * @return
     */
    private Drawable LoadImageFromWebOperations(String url) {
        try {
            InputStream is = (InputStream) new URL(url).getContent();
            d = Drawable.createFromStream(is, "src name");
            handler.sendEmptyMessage(1);
            return d;
        } catch (Exception e) {
            System.out.println("Exc=" + e);
            return null;
        }
    }

    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {
            dongtai_login_yanzheng.setText("重新获取");
            dongtai_login_yanzheng.setBackgroundColor(getResources().getColor(R.color.blue22));
        }

        @Override
        public void onTick(long millisUntilFinished) {// ��ʱ������ʾ
            String str = new SimpleDateFormat("ss").format(Long.valueOf(millisUntilFinished));
            if (str.equals("00")) {
                dongtai_login_yanzheng.setText("60秒");
            }
            dongtai_login_yanzheng.setText(str + "秒");
            dongtai_login_yanzheng.setBackgroundColor(getResources().getColor(R.color.gray98));
        }
    }
}
